package com.authentications.service;

import com.authentications.exceptions.AuthenticationUniversaException;
import com.authentications.strategy.OpenFilter;
import com.authentications.strategy.OpenOauth2;
import com.authentications.strategy.OpenSpringSecurity;
import com.authentications.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @ClassName DefaultOpen
 * @Author xiezhuocai
 * @Description 默认开关
 * @Date 2021/12/19 23:08
 */
@Configuration
public class DefaultOpen {

    private Logger logger = LoggerFactory.getLogger(DefaultOpen.class);

    @Bean
    public SpringContextUtils springContextUtils() {
        return new SpringContextUtils();
    }

    @Bean
    @ConditionalOnMissingBean({OpenFilter.class, OpenOauth2.class})
    public OpenSpringSecurity defaultOpenSpringSecurity(){
        return new OpenSpringSecurity();
    }

    @Bean
    public void inspectBean(){
        int count = 0;
        try {
            Map<String, OpenFilter> openFilterMap = SpringContextUtils.getBeansOfType(OpenFilter.class);
            if (openFilterMap.size() > 0) {
                logger.info("初始化:OpenFilter");
                count++;
            }
        } catch (Exception e){}

        try {
            Map<String, OpenSpringSecurity> beansOfType = SpringContextUtils.getBeansOfType(OpenSpringSecurity.class);
            if (beansOfType.size() > 0){
                logger.info("初始化:OpenSpringSecurity");
                count++;
            }
        } catch (Exception e){}

        try {
            Map<String, OpenOauth2> openOauth2Map = SpringContextUtils.getBeansOfType(OpenOauth2.class);
            if (openOauth2Map.size() > 0) {
                logger.info("初始化:OpenOauth2");
                count++;
            }
        } catch (Exception e){}
        if(count>1){
            throw new AuthenticationUniversaException("初始化出现错误:初始化过多策略");
        }
    }
}
